package com.spyu.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * 类加载工具类
 *
 * @author spyu
 * @date 2023-03-08
 */
public class ClassLoaderUtils {

    /**
     * 获取类加载器
     * @param clazz
     * @return
     */
    public static ClassLoader getClassLoader(Class<?> clazz) {
        if (Objects.isNull(clazz)) {
            return ClassLoader.getSystemClassLoader();
        }

        return clazz.getClassLoader();
    }

    /**
     * 获取指定路径下的Properties，并且转为Map结构
     * @param path
     * @return
     */
    public static Map<String, String> getProperties(String path) {
        ClassLoader classLoader = getClassLoader(ClassLoaderUtils.class);
        InputStream is = classLoader.getResourceAsStream(path);
        Properties props = new Properties();

        try {
            props.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Map<String, String> resultMap = new HashMap<String, String>((Map) props);
        return resultMap;
    }

    /**
     * 获取resource下的properties文件
     * @param path
     * @return
     */
    public static Properties getProperty(String path)  {
        try {
            ClassLoader classLoader = getClassLoader(ClassLoaderUtils.class);
            InputStream is = classLoader.getResourceAsStream(path);
            Properties props = new Properties();
            props.load(is);
            return props;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加载java中包名+类名的类
     * @param allClazzName 包名+类名
     * @param <T>
     * @return
     */
    public static <T> T loadClass(String allClazzName) {
        try {
            ClassLoader classLoader = getClassLoader(ClassLoaderUtils.class);
            Class<?> clazz = classLoader.loadClass(allClazzName);
            return (T) clazz.newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取对应classpath根路径下的文件
     * @param path
     * @return
     */
    public static URL getResource(String path) {
        ClassLoader classLoader = getClassLoader(ClassLoaderUtils.class);
        return classLoader.getResource(path);
    }

    /**
     * 加载指定路径下的存在相同的多个字段
     * @param path
     * @return
     */
    public static Enumeration<URL> getResources(String path) {
        ClassLoader classLoader = getClassLoader(ClassLoaderUtils.class);
        try {
            return classLoader.getResources(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
